<?php
namespace app\admin\controller\table;

use app\BaseController;
use app\common\business\table\CommonTableConfig as serviceModel;
use app\common\business\table\CommonTableNamespace as namespaceServiceModel;
use app\common\validate\table\CommonTableConfig as ValidateModel;
use think\exception\ValidateException;

class CommonTableConfig extends BaseController
{

    /*
     * 所有数组
     */
    public function list(){
        $fildes = 'page,table_name';
        $receiveData = getData($this->request->post(),$fildes);
        $where = [];
        if(!empty($receiveData['uid'])){
            $where[] = ['uid','=',$receiveData['uid']];
        }
        if(!empty($receiveData['table_name'])){
            $where[] = ['table_name','like','%'.$receiveData['table_name'].'%'];
        }
        $where[] = ['status','in',[0,1]];
        $limit_start = ($receiveData['page']-1) * env('page_size');
        $data = [
            'lists' => serviceModel::getList($where,$limit_start,env('page_size')),
            'allpage' => serviceModel::getCount($where)
        ];
        jsonSuccess($data);
    }

    /*
     * 修改和编辑
     */
    public function edit(){
        $fildes = "id,table_name,remark,status,table_namespace_id";
        $receiveData = getData($this->request->post(),$fildes);
        $admin = session('admin_user');
        try {
            if(!empty($receiveData['id'])){
                validate(validateModel::class)->scene('edit')->check($receiveData);
            }else{
                validate(validateModel::class)->scene('add')->check($receiveData);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            jsonFail($e->getError());
        }
        $where = [];
        $where[] = ['status','in',[0,1]];
        $where[] = ['table_name','=',$receiveData['table_name']];
        $load = serviceModel::getOne($where);
        if(!empty($receiveData['id'])){
            if(!empty($load) && $load['id'] != $receiveData['id']){
                jsonFail('已存在相同表名的数据');
            }
            serviceModel::edit($receiveData);
        }else{
            if(!empty($load)){
                jsonFail('已存在相同表名的数据');
            }
            serviceModel::insert($receiveData,$admin['username'].'/'.$admin['mobile']);
        }
        jsonSuccess();
    }

    public function delete(){
        $fildes = "id";
        $receiveData = getData($this->request->post(),$fildes);
        $where = [];
        $where[] = ['id','=',$receiveData['id']];
        $where[] = ['status','in',[0,1]];
        $load = serviceModel::getOne($where);
        if(empty($load)){
            jsonFail('数据不存在');
        }
        serviceModel::updateStatus('status',-1,$load);
        jsonSuccess();
    }

    /*
     * 生成class类
     */
    public function generateClass(){
        $fildes = "id";
        $receiveData = getData($this->request->post(),$fildes);
        $model = serviceModel::getOne(['id'=>$receiveData['id']]);
        $result = serviceModel::selectColumns($model);
        $namespace = namespaceServiceModel::getOne(['id'=>$model['table_namespace_id']]);
        serviceModel::generateModel($model,$namespace,$result);
        serviceModel::generateValidateModel($model,$namespace,$result);
        serviceModel::generateBusinessModel($model,$namespace,$result);
        serviceModel::generateControllerModel($model,$namespace,$result);
        serviceModel::generateApiControllerModel($model,$namespace,$result);
        serviceModel::generateFrontApi($model,$namespace);
        serviceModel::writeRoute($model,$namespace);
        serviceModel::writeApiRoute($model,$namespace);
        serviceModel::generateFrontPage($model,$namespace,$result);
        serviceModel::updateStatus('is_generate',1,$model);
        jsonSuccess();
    }

    public function generateAllClass(){
        $where = [];
        $where[] = ['status','in',[1]];
        $lists = serviceModel::getListAll($where);
        //先检查字段信息等
        if(count($lists) > 0){
            foreach ($lists as $model){
                serviceModel::selectColumns($model);
            }
            serviceModel::delDir($_SERVER['DOCUMENT_ROOT']."/generate/backend");
            serviceModel::delDir($_SERVER['DOCUMENT_ROOT']."/generate/front");
            foreach ($lists as $model){
                $result = serviceModel::selectColumns($model);
                $namespace = namespaceServiceModel::getOne(['id'=>$model['table_namespace_id']]);
                serviceModel::generateModel($model,$namespace,$result);
                serviceModel::generateValidateModel($model,$namespace,$result);
                serviceModel::generateBusinessModel($model,$namespace,$result);
                serviceModel::generateControllerModel($model,$namespace,$result);
                serviceModel::generateApiControllerModel($model,$namespace,$result);
                serviceModel::writeRoute($model,$namespace);
                serviceModel::writeApiRoute($model,$namespace);
                serviceModel::generateFrontApi($model,$namespace);
                serviceModel::generateFrontPage($model,$namespace,$result);
                serviceModel::updateStatus('is_generate',1,$model);
            }
            serviceModel::generateFrontRoute();
            serviceModel::generateSqlMenu();
            jsonSuccess([],'生成成功');
        }
        jsonSuccess([],'没有要生成的表单');
    }

    /*
     * 压缩文件并下载
     */
    public function zipModule(){
        //先判断压缩文件是否存在，存在的话先删除
        $dir = $_SERVER['DOCUMENT_ROOT']."/generate.zip";
        if(file_exists($dir)){
            unlink($dir);
        }
        require_once $_SERVER["DOCUMENT_ROOT"] . '/../extend/Zip.php';
        $zip = new \Zip();
        $zip->zipDir($_SERVER['DOCUMENT_ROOT']."/generate",$_SERVER['DOCUMENT_ROOT']."/generate.zip");
        $data = [
            'href' => env('api_url').'/generate.zip'
        ];
        jsonSuccess($data);
    }

    public function test(){
        //serviceModel::generateFrontRoute();
        serviceModel::generateSqlMenu();
    }

}
